package com.xuetang9.fujian.view;

import com.xuetang9.fujian.model.User;

import javax.swing.*;
import javax.swing.text.*;
import java.awt.*;
import java.awt.event.*;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.concurrent.TimeUnit;

/**
 * @author: fujian
 * @description:聊天界面
 * @date: 2021/6/8 10:52
 * @version: V1.0
 * @package: com.xuetang9.fujian.view
 **/
@SuppressWarnings("all")
public class ChatFrame extends JFrame {
    private JSplitPane splitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT,true);
    private JTextPane recordsTextPanel = new JTextPane();
    private JPanel chatOperationPanel = new JPanel();
    private JPanel toolPanel = new JPanel();
    private JButton faceButton = new JButton();
    private JButton gifButton = new JButton();
    private JButton cutButton = new JButton("cut");
    private JButton fileButton = new JButton();
    private JButton imageButton = new JButton();
    private JButton shakeButton = new JButton("shake");
    private JButton moreButton = new JButton();
    private JTextPane inputTextPanel = new JTextPane();
    private JButton sendButton = new JButton("send");
    private JButton closeButton = new JButton("close");
    private JPanel sendPanel = new JPanel();
    private JPanel contentPanel = null;
    private User relationPerson;
    public ChatFrame(){
        init();
        setVisible(true);
    }

    public ChatFrame(User user){
        this.relationPerson = user;
        init();
        setVisible(true);
    }

    private void init() {
        setTitle("chatting with [" + relationPerson.getNickName() + "]");
        setSize(new Dimension(775,680));
        setLocationRelativeTo(null);
//        setDefaultCloseOperation(EXIT_ON_CLOSE);
        contentPanel = (JPanel) getContentPane();
        // configure components
        configSplitPanel();
        configRecordsTextPanel();
        configChatOperationPanel();
        // install components
        installComponents();
        
        // install componets events
        installListeners();
    }

    private void configSplitPanel() {
        splitPane.setDividerSize(5);
        splitPane.setResizeWeight(0.7);
    }

    private void configRecordsTextPanel() {
        recordsTextPanel.setEditable(false);
//        recordsTextPanel.setText("test text");
    }

    private void configChatOperationPanel() {
        // set top toolPanel
        configToolPanel();
        chatOperationPanel.setLayout(new BorderLayout());
        configInputTextPanel();
        configSendPane();
    }

    private void configToolPanel() {
        toolPanel.setLayout(new FlowLayout(FlowLayout.LEFT,8,0));
        toolPanel.setPreferredSize(new Dimension(0,38));
        toolPanel.setBorder(BorderFactory.createEmptyBorder(4,0,5,0));
    }

    private void configInputTextPanel(){
        // she zhi nenggou huanhang

    }

    private void configSendPane(){
        sendPanel.setLayout(new FlowLayout(FlowLayout.RIGHT));
        sendPanel.setPreferredSize(new Dimension(0,50));
//        sendPanel.setBorder(BorderFactory.createLineBorder(Color.BLACK,2));
    }

    private JScrollPane creatScrollPanel(JTextPane textPane){
        JScrollPane scrollPane = new JScrollPane(textPane);
        scrollPane.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
        return scrollPane;
    }

    private void installComponents() {
        toolPanel.add(faceButton);
        toolPanel.add(gifButton);
        toolPanel.add(cutButton);
        toolPanel.add(fileButton);
        toolPanel.add(imageButton);
        toolPanel.add(shakeButton);
        toolPanel.add(moreButton);
        chatOperationPanel.add(toolPanel,BorderLayout.NORTH);
        sendPanel.add(sendButton);
        sendPanel.add(closeButton);
        chatOperationPanel.add(sendPanel,BorderLayout.SOUTH);
        chatOperationPanel.add(creatScrollPanel(inputTextPanel),BorderLayout.CENTER);
        splitPane.setTopComponent(creatScrollPanel(recordsTextPanel));
        splitPane.setBottomComponent(chatOperationPanel);
        contentPanel.add(splitPane);
    }

    private void installListeners() {
        sendButton.addActionListener(new SendButtonHandler());
        inputTextPanel.addKeyListener(new SendButtonHandler());
        cutButton.addActionListener(new CutButtonHandler());
        shakeButton.addActionListener(new ShakeButtonHandler());
        addWindowListener(new WindowCloseHandler());
    }
    /**
     * @desc append chat title to contentPanel,
     * whick need to show the person nickname and send datetime who send this message
     * @param null
     * @return  
     * @author fujian
     * @date 2021/6/9 14:39:29
     * @version 1.0
     **/
    public void appendContentTitle(String contentTitle){
        StyledDocument styledDocument = recordsTextPanel.getStyledDocument();
        SimpleAttributeSet attributeSet = new SimpleAttributeSet();
        StyleConstants.setFontFamily(attributeSet,"宋体");
        StyleConstants.setFontSize(attributeSet,16);
        StyleConstants.setBold(attributeSet,true);
        LocalDateTime localDateTime = LocalDateTime.now();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        String date = formatter.format(localDateTime);
        try {
            styledDocument.insertString(styledDocument.getLength(),contentTitle + System.getProperty("line.separator"),attributeSet);
            StyleConstants.setFontSize(attributeSet,15);
            StyleConstants.setForeground(attributeSet,Color.RED);
            styledDocument.insertString(styledDocument.getLength(),date + System.getProperty("line.separator"),attributeSet);
        } catch (BadLocationException e) {
            e.printStackTrace();
        }
    }

    public void appendContentMessage(String message){
        appendSpaceLine();
        StyledDocument styledDocument = recordsTextPanel.getStyledDocument();
        SimpleAttributeSet attributeSet = new SimpleAttributeSet();
        StyleConstants.setFontFamily(attributeSet,"宋体");
        StyleConstants.setFontSize(attributeSet,14);
        StyleConstants.setBold(attributeSet,true);
        try {
            styledDocument.insertString(styledDocument.getLength(),message + System.getProperty("line.separator"),attributeSet);
        } catch (BadLocationException e) {
            e.printStackTrace();
        }
        appendSpaceLine();
    }

    public void appendContentMessage(StyledDocument document){
        appendSpaceLine();
        for (int i = 0; i < document.getLength(); i++) {
            int offset = recordsTextPanel.getStyledDocument().getLength();
            recordsTextPanel.setCaretPosition(offset);
            Element element = document.getCharacterElement(i);
            if (element.getName().equals(StyleConstants.IconElementName)){
                recordsTextPanel.insertIcon(StyleConstants.getIcon(element.getAttributes()));
            }else{
                try {
                    recordsTextPanel.getStyledDocument().insertString(offset,document.getText(i,1),null);
                } catch (BadLocationException e) {
                    e.printStackTrace();
                }
                System.out.println("insert string");
            }
        }
        appendSpaceLine();
    }


    private void appendSpaceLine() {
        StyledDocument styledDocument = recordsTextPanel.getStyledDocument();
        SimpleAttributeSet attributeSet = new SimpleAttributeSet();
        StyleConstants.setFontFamily(attributeSet,"宋体");
        StyleConstants.setFontSize(attributeSet,4);
        StyleConstants.setBold(attributeSet,true);
        try {
            styledDocument.insertString(styledDocument.getLength(),"" + System.getProperty("line.separator"),attributeSet);
        } catch (BadLocationException e) {
            e.printStackTrace();
        }
    }

    public void setCaptureImage(Image image){
        inputTextPanel.insertIcon(new ImageIcon(image));
    }

    public void shakeWindow(){
        Point location = getLocation();
        int distance = 5;
        for (int i = 0; i < 10; i++) {
            distance = -distance;
            setLocation(location.x + distance,location.y);
            try {
                TimeUnit.MILLISECONDS.sleep(10);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        setLocation(location);
    }

    private class SendButtonHandler extends KeyAdapter implements ActionListener{
        @Override
        public void keyPressed(KeyEvent e) {
            if (e.getKeyCode() == KeyEvent.VK_ENTER && e.isShiftDown()){
                StyledDocument styledDocument = inputTextPanel.getStyledDocument();
                if (styledDocument.getLength() == 0) return;
                inputTextPanel.setStyledDocument(new DefaultStyledDocument());
                appendContentTitle("to coco ");
                appendContentMessage(styledDocument);
            }
        }

        @Override
        public void actionPerformed(ActionEvent e) {
            StyledDocument styledDocument = inputTextPanel.getStyledDocument();
            if (styledDocument.getLength() == 0) return;
            inputTextPanel.setStyledDocument(new DefaultStyledDocument());
            appendContentTitle("to coco ");
            appendContentMessage(styledDocument);
        }
    }

    private class CutButtonHandler implements ActionListener{

        @Override
        public void actionPerformed(ActionEvent e) {
            new ScreenFrame(ChatFrame.this);
        }
    }

    private class ShakeButtonHandler implements ActionListener{

        @Override
        public void actionPerformed(ActionEvent e) {
            ChatFrame.this.shakeWindow();
        }
    }

    private class WindowCloseHandler extends WindowAdapter{
        @Override
        public void windowClosing(WindowEvent e) {
            WindowManager.closeChatFrame(relationPerson.getAccount());
        }
    }

    public static void main(String[] args) {
        ChatFrame chatFrame = new ChatFrame();
        chatFrame.appendContentTitle("chatting to fujian");
        chatFrame.appendContentMessage("eat?");
    }
}
